<?php

require_once 'Client.php';

/**
 *  zend db table
 */
class Application_Model_DbTable_Clients extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_client';
}


/**
 *  
 */
class Clients extends BaseMapper
{
    protected $_modelName   = 'Client';
    protected $_dbTableName = 'Application_Model_DbTable_Clients';

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  add Client
     */
    public function addClient( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update Client
     */
    public function updateClient( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /**
     *  get Client
     */
    public function getClient( $id, $status=NULL )
    {
        $model = $this->_find($id);
        if( NULL !== $status AND $model->getStatus() !== $status ) {
            return false;
        }
        return $model;
    }

    /**
     *  find Clients
     */
    public function findClients( $clientId=0, $searchKey='', $page=1, $rowCount=BaseMapper::DEFAULT_ROW_COUNT ) 
    {
        $opt = Array(
            'clientId'   => $clientId,
            '_orderBy'   => ' id DESC ',
            '_searchKey' => $searchKey,
            '_page'      => $page,
            '_rowCount'  => $rowCount,
        );
        return $this->_getByQuery($opt);
    }
    /**
     *  get Client count
     */
    public function getNumByFindClients( $clientId=0, $searchKey='' ) 
    {
        $opt = Array(
            'clientId'   => $clientId,
            '_searchKey' => $searchKey,
        );
        return $this->_getByQuery($opt,true);
    }

    /**
     *  add many Client Dependant by client id
     */
    public function getClientDependantsById( $clientId ) 
    {
        $opt = Array(
            'clientId'   => $clientId,
            '_orderBy'   => ' id DESC ',
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get Client query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'id'                   => (ISSET($opt['id'])                   ? (int) ($opt['id'])                   : NULL ),
            'userId'               => (ISSET($opt['userId'])               ? (int) ($opt['userId'])               : NULL ),
            'clientId'             => (ISSET($opt['clientId'])             ? (int) ($opt['clientId'])             : NULL ),
            'name'                 => (ISSET($opt['name'])                 ?       ($opt['name'])                 : NULL ),
            'email'                => (ISSET($opt['email'])                ?       ($opt['email'])                : NULL ),
            'tel'                  => (ISSET($opt['tel'])                  ?       ($opt['tel'])                  : NULL ),
            'phone'                => (ISSET($opt['phone'])                ?       ($opt['phone'])                : NULL ),
            'addressNumber'        => (ISSET($opt['addressNumber'])        ?       ($opt['addressNumber'])        : NULL ),
            'address'              => (ISSET($opt['address'])              ?       ($opt['address'])              : NULL ),
            'birthday'             => (ISSET($opt['birthday'])             ?       ($opt['birthday'])             : NULL ),
            'memo'                 => (ISSET($opt['memo'])                 ?       ($opt['memo'])                 : NULL ),
            'updateDate'           => (ISSET($opt['updateDate'])           ?       ($opt['updateDate'])           : NULL ),
            'properties'           => (ISSET($opt['properties'])           ?       ($opt['properties'])           : NULL ),

            '_startDate'           => (ISSET($opt['_startDate'])           ?       ($opt['_startDate'])           : NULL ),
            '_endDate'             => (ISSET($opt['_endDate'])             ?       ($opt['_endDate'])             : NULL ),
            '_searchKey'           => (ISSET($opt['_searchKey'])           ?       ($opt['_searchKey'])           : NULL ),
            '_orderBy'             => (ISSET($opt['_orderBy'])             ?       ($opt['_orderBy'])             : ' id DESC ' ),
            '_page'                => (ISSET($opt['_page'])                ? (int) ($opt['_page'])                : 1 ),
            '_rowCount'            => (ISSET($opt['_rowCount'])            ? (int) ($opt['_rowCount'])            : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(ISSET( $opt['id']                  )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' id = ? '                  , $opt['id']                   );  }
        if(ISSET( $opt['userId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' user_id = ? '             , $opt['userId']               );  }
        if(ISSET( $opt['clientId']            )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' client_id = ? '           , $opt['clientId']             );  }
        if(ISSET( $opt['name']                )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' name = ? '                , $opt['name']                 );  }
        if(ISSET( $opt['email']               )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' email = ? '               , $opt['email']                );  }
        if(ISSET( $opt['tel']                 )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' tel = ? '                 , $opt['tel']                  );  }
        if(ISSET( $opt['phone']               )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' phone = ? '               , $opt['phone']                );  }
        if(ISSET( $opt['addressNumber']       )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' address_number = ? '      , $opt['addressNumber']        );  }
        if(ISSET( $opt['address']             )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' address = ? '             , $opt['address']              );  }
        if(ISSET( $opt['birthday']            )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' birthday = ? '            , $opt['birthday']             );  }
        if(ISSET( $opt['memo']                )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' memo = ? '                , $opt['memo']                 );  }
        if(ISSET( $opt['updateDate']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' update_date = ? '         , $opt['updateDate']           );  }
        if(ISSET( $opt['properties']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' properties = ? '          , $opt['properties']           );  }

        if( $opt['_searchKey'] ) {
            // 注意: 特殊符號應該要變更一下 => "%" "_" 之類的
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' name    LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' email   LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' tel     LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' phone   LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' address LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' memo    LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $where[] = ' ( '. join(' OR ',$searchTerms) . ' ) ';
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select
                ->from( $this->getDb(), Array('COUNT(id) AS total') )
                ->where( join(' AND ',$where) );
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo join(' AND ',$where); exit;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll(join(' AND ',$where), $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll(join(' AND ',$where), $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function mapRow($row)
    {
        //properties
        is_array($row["properties"])
            ? $row["properties"] = unserialize($row["properties"])
            : $row["properties"] = Array();

        $model = $this->getModel();
        $model->setId                   ( $row['id']                   );
        $model->setUserId               ( $row['user_id']              );
        $model->setClientId             ( $row['client_id']            );
        $model->setName                 ( $row['name']                 );
        $model->setEmail                ( $row['email']                );
        $model->setTel                  ( $row['tel']                  );
        $model->setPhone                ( $row['phone']                );
        $model->setAddressNumber        ( $row['address_number']       );
        $model->setAddress              ( $row['address']              );
        $model->setBirthday             ( strtotime($row['birthday'])  );
        $model->setMemo                 ( $row['memo']                 );
        $model->setUpdateDate           ( strtotime($row['update_date']) );
        $model->setProperties           ( $row['properties']           );
        return $model;
    }

}

